package top.llove.config.impl;

import cn.hutool.extra.servlet.ServletUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.llove.utils.res.ApiResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


/**
 * 自定义过滤器
 * @author: 幸会
 * @date: 2021/6/6 15:14
 * @email: 1846724873@qq.com
 * @description: MyHandlerInterceptor
 * version: 1.0
 */
@Slf4j
@Component
public class MyHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate; // Redis

    @Autowired
    private ApiResult res;

    @Autowired
    private ObjectMapper om;

    private Long start;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object h) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");

        start = System.currentTimeMillis();

        String url = req.getRequestURI(); // 获取请求URL
        String ip = ServletUtil.getClientIP(req); // 获取请求客户端IP
        log.info("请求IP: " + ip + ", 请求URL: " + url);
        /*String token = req.getHeader("token");

        System.out.println(ip);

        if (token != "" && token != null) {
            String tokenRes = (String) redisTemplate.opsForValue().get(token);
            if (tokenRes != "" && tokenRes != null) {
                res = ApiResult.success(200, "用户正常", true);
            }
            res = ApiResult.fail(404, "登录失效, 请重新登录", false);
        } else {
            res = ApiResult.fail(404, "token不能为空", false);
        }
        resp.getWriter().write(om.writeValueAsString(res));
        return (boolean) res.getData();*/
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception ex) throws Exception {
        Long end = System.currentTimeMillis();
        log.info("当前请求URL: " + req.getRequestURI() + ", 请求耗时: " + (end - start) + "毫秒");
    }
}
